#!/usr/bin/env python

import os
import struct
import sys
import warnings

MASKS = {'ASIC_ROW':   0x30000000,
         'ASIC_COL':   0x03000000,
         'PACKET_NO':  0x00FF0000,
         'ASIC_CHAN':  0x00007000,         
         'ORIGIN_WIN': 0x000001FF,
         }

def read_packet(f):
    nbytes = 140*4
    bytestr = f.read(nbytes)

    if len(bytestr) != nbytes:
        if len(bytestr) == 0:
            return []
        else:
            msg = "Read {0} bytes and then encountered EOF"
            warnings.warn(msg.format(len(bytestr)))
            return []
                          
#            raise IOError(msg.format(len(bytestr)))
    
    return struct.unpack("140I", bytestr)


rows  = set()
cols  = set()
chans = set()
wins  = set()

for i, path in enumerate(sys.argv[1:]):
    sys.stdout.write("{0}/{1} files parsed\r".format(i, len(sys.argv[1:])))
    sys.stdout.flush()

    fsize    = os.stat(path).st_size
    nwords_in_file = fsize / 4
    if nwords_in_file % 140 != 0:
        msg = "File `%s' has file size of %d words (%d bytes), " + \
            "which is not a multiple of 140"
        warnings.warn(msg % (path, nwords_in_file, fsize))
    
    npkts = nwords_in_file / 140

    with open(path) as fpin:
        words = read_packet(fpin)
        while len(words) > 0:
            if words[0] != 0xbe11e2:
                msg = "Packet reading failed; first word of packet was {0:x}"
                raise ValueError(msg.format(words[0]))

            if words[3] != 0xc0ffee:
                words = read_packet(fpin)
                continue

            for i in xrange(4):
                origin = words[5 + i*33]
            
                rows.add((origin & MASKS['ASIC_ROW']) >> 28)
                cols.add((origin & MASKS['ASIC_COL']) >> 24)                 
                chans.add((origin & MASKS['ASIC_CHAN']) >> 12)
                wins.add(origin & MASKS['ORIGIN_WIN'])            

            words = read_packet(fpin)

print "{0}/{0} files parsed\r".format(len(sys.argv[1:]))

print "rows:", rows
print "cols:", cols
print "chans:", chans
print "wins:", wins

